<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>C++ 使用 chrono 库处理日期和时间 | 逝水无痕の博客</title><meta name="keywords" content="c++,chrono"><meta name="author" content="逝水无痕"><meta name="copyright" content="逝水无痕"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="C++ 使用 chrono 库处理日期和时间C++11 中提供了日期和时间相关的库 chrono，通过 chrono 库可以很方便地处理日期和时间，为程序的开发提供了便利。chrono 库主要包含三种类型的类：时间间隔duration、时钟clocks、时间点time point。 1. 时间间隔 duration1.1 常用类成员duration表示一段时间间隔，用来记录时间长度，可以表示几秒、">
<meta property="og:type" content="article">
<meta property="og:title" content="C++ 使用 chrono 库处理日期和时间">
<meta property="og:url" content="https://hexo.zyjblogs.cn/posts/c++/library/date/1.html">
<meta property="og:site_name" content="逝水无痕の博客">
<meta property="og:description" content="C++ 使用 chrono 库处理日期和时间C++11 中提供了日期和时间相关的库 chrono，通过 chrono 库可以很方便地处理日期和时间，为程序的开发提供了便利。chrono 库主要包含三种类型的类：时间间隔duration、时钟clocks、时间点time point。 1. 时间间隔 duration1.1 常用类成员duration表示一段时间间隔，用来记录时间长度，可以表示几秒、">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg">
<meta property="article:published_time" content="2022-02-06T16:00:00.000Z">
<meta property="article:modified_time" content="2022-02-08T08:37:27.151Z">
<meta property="article:author" content="逝水无痕">
<meta property="article:tag" content="c++">
<meta property="article:tag" content="chrono">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="https://hexo.zyjblogs.cn/posts/c++/library/date/1"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//hm.baidu.com"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?6edd69cc926242ec43e7194677fb8040";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#121212","position":"bottom-left"},
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'C++ 使用 chrono 库处理日期和时间',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-02-08 16:37:27'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if (GLOBAL_CONFIG_SITE.isHome && /iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    document.addEventListener('pjax:complete', detectApple)})(window)</script><link rel="stylesheet" href="_static/css/background.css"><meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/atom.xml" title="逝水无痕の博客" type="application/atom+xml">
<link rel="alternate" href="/rss2.xml" title="逝水无痕の博客" type="application/rss+xml">
</head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://zyjblogs.cn/logo.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">11</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">8</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">5</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 媒体</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/bangumis"><i class="fa-fw fa-fw fab fa-youtube"></i><span> 番剧</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">逝水无痕の博客</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 媒体</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/bangumis"><i class="fa-fw fa-fw fab fa-youtube"></i><span> 番剧</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">C++ 使用 chrono 库处理日期和时间</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-02-06T16:00:00.000Z" title="发表于 2022-02-07 00:00:00">2022-02-07</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-02-08T08:37:27.151Z" title="更新于 2022-02-08 16:37:27">2022-02-08</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/c/">c++</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">4.8k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>19分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="C++ 使用 chrono 库处理日期和时间"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="C-使用-chrono-库处理日期和时间"><a href="#C-使用-chrono-库处理日期和时间" class="headerlink" title="C++ 使用 chrono 库处理日期和时间"></a>C++ 使用 chrono 库处理日期和时间</h1><p>C++11 中提供了日期和时间相关的库 chrono，通过 chrono 库可以很方便地处理日期和时间，为程序的开发提供了便利。chrono 库主要包含三种类型的类：时间间隔duration、时钟clocks、时间点time point。</p>
<h2 id="1-时间间隔-duration"><a href="#1-时间间隔-duration" class="headerlink" title="1. 时间间隔 duration"></a>1. 时间间隔 duration</h2><h3 id="1-1-常用类成员"><a href="#1-1-常用类成员" class="headerlink" title="1.1 常用类成员"></a>1.1 常用类成员</h3><p>duration表示一段时间间隔，用来记录时间长度，可以表示几秒、几分钟、几个小时的时间间隔。duration 的原型如下：</p>
<figure class="highlight cpp"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 定义于头文件 &lt;chrono&gt;</span></span><br><span class="line"><span class="keyword">template</span>&lt;</span><br><span class="line">    <span class="class"><span class="keyword">class</span> <span class="title">Rep</span>,</span></span><br><span class="line"><span class="class">    <span class="keyword">class</span> <span class="title">Period</span> =</span> std::ratio&lt;<span class="number">1</span>&gt;</span><br><span class="line">&gt; <span class="class"><span class="keyword">class</span> <span class="title">duration</span>;</span></span><br></pre></td></tr></table></figure>

<p>ratio 类表示每个时钟周期的秒数，其中第一个模板参数 Num 代表分子，Denom 代表分母，该分母值默认为 1，因此，ratio 代表的是一个分子除以分母的数值，比如：<code>ratio&lt;2&gt;</code> 代表一个时钟周期是 2 秒，<code>ratio&lt;60 &gt;</code> 代表一分钟，<code>ratio&lt;60*60 &gt;</code> 代表一个小时，<code>ratio&lt;60*60*24 &gt;</code> 代表一天。而 <code>ratio&lt;1,1000 &gt;</code> 代表的是 <code>1/1000</code> 秒，也就是 1 毫秒，<code>ratio&lt;1,1000000 &gt;</code> 代表一微秒，<code>ratio&lt;1,1000000000 &gt;</code> 代表一纳秒。</p>
<blockquote>
<p>为了方便使用，在标准库中定义了一些常用的时间间隔，比如：时、分、秒、毫秒、微秒、纳秒，它们都位于 chrono 命名空间下，定义如下：</p>
</blockquote>
<table>
<thead>
<tr>
<th align="left">类型</th>
<th align="center">定义</th>
</tr>
</thead>
<tbody><tr>
<td align="left">纳秒：<code>std::chrono::nanoseconds</code></td>
<td align="center"><code>duration&lt;Rep</code><em>/</em> 至少 64 位的有符号整数类型 <em>/</em>, <code>std::nano&gt;</code></td>
</tr>
<tr>
<td align="left">微秒：<code>std::chrono::microseconds</code></td>
<td align="center"><code>duration&lt;Rep</code><em>/</em> 至少 55 位的有符号整数类型 <em>/</em>, <code>std::micro&gt;</code></td>
</tr>
<tr>
<td align="left">毫秒：<code>std::chrono::milliseconds</code></td>
<td align="center"><code>duration&lt;Rep</code><em>/</em> 至少 45 位的有符号整数类型 <em>/</em>, <code>std::milli&gt;</code></td>
</tr>
<tr>
<td align="left">秒：<code>std::chrono::seconds</code></td>
<td align="center"><code>duration&lt;Rep</code><em>/</em> 至少 35 位的有符号整数类型 <em>/</em>&gt;</td>
</tr>
<tr>
<td align="left">分钟：<code>std::chrono::minutes</code></td>
<td align="center"><code>duration&lt;Rep</code><em>/</em> 至少 29 位的有符号整数类型 <em>/</em>, <code>std::ratio&lt;60&gt;&gt;</code></td>
</tr>
<tr>
<td align="left">小时：<code>std::chrono::hours</code></td>
<td align="center"><code>duration&lt;Rep</code><em>/</em> 至少 23 位的有符号整数类型 <em>/</em>, <code>std::ratio&lt;3600&gt;&gt;</code></td>
</tr>
</tbody></table>
<p><strong>注意</strong>：到 hours 为止的每个预定义时长类型至少涵盖 ±292 年的范围。</p>
<blockquote>
<p>duration 类的构造函数原型如下：</p>
</blockquote>
<figure class="highlight cpp"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 1. 拷贝构造函数</span></span><br><span class="line"><span class="built_in">duration</span>( <span class="keyword">const</span> duration&amp; ) = <span class="keyword">default</span>;</span><br><span class="line"><span class="comment">// 2. 通过指定时钟周期的类型来构造对象</span></span><br><span class="line"><span class="function"><span class="keyword">template</span>&lt; class Rep2 &gt;</span></span><br><span class="line"><span class="function"><span class="keyword">constexpr</span> <span class="keyword">explicit</span> <span class="title">duration</span><span class="params">( <span class="keyword">const</span> Rep2&amp; r )</span></span>;</span><br><span class="line"><span class="comment">// 3. 通过指定时钟周期类型，和时钟周期长度来构造对象</span></span><br><span class="line"><span class="function"><span class="keyword">template</span>&lt; class Rep2, class Period2 &gt;</span></span><br><span class="line"><span class="function"><span class="keyword">constexpr</span> <span class="title">duration</span><span class="params">( <span class="keyword">const</span> duration&lt;Rep2,Period2&gt;&amp; d )</span></span>;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>为了更加方便的进行 duration 对象之间的操作，类内部进行了操作符重载：</p>
</blockquote>
<table>
<thead>
<tr>
<th align="left">操作符重载</th>
<th align="center">描述</th>
</tr>
</thead>
<tbody><tr>
<td align="left">operator=</td>
<td align="center">赋值内容 (公开成员函数)</td>
</tr>
<tr>
<td align="left">operator+ operator-</td>
<td align="center">赋值内容 (公开成员函数)</td>
</tr>
<tr>
<td align="left">operator++ operator++(int) operator– operator–(int)</td>
<td align="center">递增或递减周期计数 (公开成员函数)</td>
</tr>
<tr>
<td align="left">operator+= operator-= operator*= operator/= operator%=</td>
<td align="center">实现二个时长间的复合赋值 (公开成员函数)</td>
</tr>
</tbody></table>
<blockquote>
<p>duration 类还提供了获取时间间隔的时钟周期数的方法 count ()，函数原型如下：</p>
</blockquote>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">constexpr rep count() const;</span><br></pre></td></tr></table></figure>

<h3 id="1-2-类的使用"><a href="#1-2-类的使用" class="headerlink" title="1.2 类的使用"></a>1.2 类的使用</h3><blockquote>
<p>通过构造函数构造事件间隔对象示例代码如下：</p>
</blockquote>
<figure class="highlight cpp"><table><tr><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;chrono&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> std;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="function">chrono::hours <span class="title">h</span><span class="params">(<span class="number">1</span>)</span></span>;                          <span class="comment">// 一小时</span></span><br><span class="line">    chrono::milliseconds ms&#123; <span class="number">3</span> &#125;;                <span class="comment">// 3 毫秒</span></span><br><span class="line">    chrono::duration&lt;<span class="keyword">int</span>, ratio&lt;<span class="number">1000</span>&gt;&gt; <span class="built_in">ks</span>(<span class="number">3</span>);    <span class="comment">// 3000 秒</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// chrono::duration&lt;int, ratio&lt;1000&gt;&gt; d3(3.5);  // error</span></span><br><span class="line">    <span class="function">chrono::duration&lt;<span class="keyword">double</span>&gt; <span class="title">dd</span><span class="params">(<span class="number">6.6</span>)</span></span>;               <span class="comment">// 6.6 秒</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// 使用小数表示时钟周期的次数</span></span><br><span class="line">    chrono::duration&lt;<span class="keyword">double</span>, std::ratio&lt;<span class="number">1</span>, <span class="number">30</span>&gt;&gt; <span class="built_in">hz</span>(<span class="number">3.5</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>h(1) 时钟周期为 1 小时，共有 1 个时钟周期，所以 h 表示的时间间隔为 1 小时</li>
<li>ms(3) 时钟周期为 1 毫秒，共有 3 个时钟周期，所以 ms 表示的时间间隔为 3 毫秒</li>
<li>ks(3) 时钟周期为 1000 秒，一共有三个时钟周期，所以 ks 表示的时间间隔为 3000 秒</li>
<li>d3(3.5) 时钟周期为 1000 秒，时钟周期数量只能用整形来表示，但是此处指定的是浮点数，因此语法错误</li>
<li>dd(6.6) 时钟周期为默认的 1 秒，共有 6.6 个时钟周期，所以 dd 表示的时间间隔为 6.6 秒</li>
<li>hz(3.5) 时钟周期为 1/30 秒，共有 3.5 个时钟周期，所以 hz 表示的时间间隔为 1/30*3.5 秒</li>
</ul>
<p>chrono 库中根据 duration 类封装了不同长度的时钟周期（也可以自定义），基于这个时钟周期再进行周期次数的设置就可以得到总的时间间隔了（时钟周期 * 周期次数 = 总的时间间隔）。</p>
<p>示例代码如下：</p>
<figure class="highlight cpp"><table><tr><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;chrono&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    std::chrono::milliseconds ms&#123;<span class="number">3</span>&#125;;         <span class="comment">// 3 毫秒</span></span><br><span class="line">    std::chrono::microseconds us = <span class="number">2</span>*ms;     <span class="comment">// 6000 微秒</span></span><br><span class="line">    <span class="comment">// 时间间隔周期为 1/30 秒</span></span><br><span class="line">    std::chrono::duration&lt;<span class="keyword">double</span>, std::ratio&lt;<span class="number">1</span>, <span class="number">30</span>&gt;&gt; <span class="built_in">hz</span>(<span class="number">3.5</span>);</span><br><span class="line"> </span><br><span class="line">    std::cout &lt;&lt;  <span class="string">&quot;3 ms duration has &quot;</span> &lt;&lt; ms.<span class="built_in">count</span>() &lt;&lt; <span class="string">&quot; ticks\n&quot;</span></span><br><span class="line">              &lt;&lt;  <span class="string">&quot;6000 us duration has &quot;</span> &lt;&lt; us.<span class="built_in">count</span>() &lt;&lt; <span class="string">&quot; ticks\n&quot;</span></span><br><span class="line">              &lt;&lt;  <span class="string">&quot;3.5 hz duration has &quot;</span> &lt;&lt; hz.<span class="built_in">count</span>() &lt;&lt; <span class="string">&quot; ticks\n&quot;</span>;       </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出的结果为：</p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">3 ms duration has 3 ticks</span><br><span class="line">6000 us duration has 6000 ticks</span><br><span class="line">3.5 hz duration has 3.5 ticks</span><br></pre></td></tr></table></figure>

<ul>
<li>ms 时间单位为毫秒，初始化操作 ms{3} 表示时间间隔为 3 毫秒，一共有 3 个时间周期，每个周期为 1 毫秒</li>
<li>us 时间单位为微秒，初始化操作 2*ms 表示时间间隔为 6000 微秒，一共有 6000 个时间周期，每个周期为 1 微秒</li>
<li>hz 时间单位为秒，初始化操作 hz(3.5) 表示时间间隔为 1/30*3.5 秒，一共有 3.5 个时间周期，每个周期为 1/30 秒</li>
</ul>
<p>由于在 duration 类内部做了操作符重载，因此时间间隔之间可以直接进行算术运算，比如我们要计算两个时间间隔的差值，就可以在代码中做如下处理：</p>
<figure class="highlight cpp"><table><tr><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;chrono&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> std;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="function">chrono::minutes <span class="title">t1</span><span class="params">(<span class="number">10</span>)</span></span>;</span><br><span class="line">    <span class="function">chrono::seconds <span class="title">t2</span><span class="params">(<span class="number">60</span>)</span></span>;</span><br><span class="line">    chrono::seconds t3 = t1 - t2;</span><br><span class="line">    cout &lt;&lt; t3.<span class="built_in">count</span>() &lt;&lt; <span class="string">&quot; second&quot;</span> &lt;&lt; endl;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>程序输出的结果：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">540 second</span><br></pre></td></tr></table></figure>

<p>在上面的测试程序中，t1 代表 10 分钟，t2 代表 60 秒，t3 是 t1 减去 t2，也就是 60*10-60=540，这个 540 表示的时钟周期，每个时钟周期是 1 秒，因此两个时间间隔之间的差值为 540 秒。</p>
<blockquote>
<p>注意事项：duration 的加减运算有一定的规则，当两个 duration 时钟周期不相同的时候，会先统一成一种时钟，然后再进行算术运算，统一的规则如下：假设有 ratio&lt;x1,y1&gt; 和 ratio&lt;x2,y2 &gt; 两个时钟周期，首先需要求出 x1，x2 的最大公约数 X，然后求出 y1，y2 的最小公倍数 Y，统一之后的时钟周期 ratio 为 ratio&lt;X,Y&gt;。</p>
</blockquote>
<figure class="highlight cpp"><table><tr><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;chrono&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> std;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    chrono::duration&lt;<span class="keyword">double</span>, ratio&lt;<span class="number">9</span>, <span class="number">7</span>&gt;&gt; <span class="built_in">d1</span>(<span class="number">3</span>);</span><br><span class="line">    chrono::duration&lt;<span class="keyword">double</span>, ratio&lt;<span class="number">6</span>, <span class="number">5</span>&gt;&gt; <span class="built_in">d2</span>(<span class="number">1</span>);</span><br><span class="line">    <span class="comment">// d1 和 d2 统一之后的时钟周期</span></span><br><span class="line">    chrono::duration&lt;<span class="keyword">double</span>, ratio&lt;<span class="number">3</span>, <span class="number">35</span>&gt;&gt; d3 = d1 - d2;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>对于分子 6,、9 最大公约数为 3，对于分母 7、5 最小公倍数为 35，因此推导出的时钟周期为 ratio&lt;3,35&gt;</p>
<h3 id="2-时间点-time-point"><a href="#2-时间点-time-point" class="headerlink" title="2. 时间点 time point"></a>2. 时间点 time point</h3><p>chrono 库中提供了一个表示时间点的类 time_point，该类的定义如下：</p>
<figure class="highlight cpp"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 定义于头文件 &lt;chrono&gt;</span></span><br><span class="line"><span class="keyword">template</span>&lt;</span><br><span class="line">    <span class="class"><span class="keyword">class</span> <span class="title">Clock</span>,</span></span><br><span class="line"><span class="class">    <span class="keyword">class</span> <span class="title">Duration</span> =</span> <span class="keyword">typename</span> Clock::duration</span><br><span class="line">&gt; <span class="class"><span class="keyword">class</span> <span class="title">time_point</span>;</span></span><br></pre></td></tr></table></figure>

<p>它被实现成如同存储一个 Duration 类型的自 Clock 的纪元起始开始的时间间隔的值，通过这个类最终可以得到时间中的某一个时间点。</p>
<ul>
<li>Clock：此时间点在此时钟上计量</li>
<li>Duration：用于计量从纪元起时间的 std::chrono::duration 类型</li>
</ul>
<blockquote>
<p>time_point 类的构造函数原型如下：</p>
</blockquote>
<figure class="highlight cpp"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 1. 构造一个以新纪元(epoch，即：1970.1.1)作为值的对象，需要和时钟类一起使用，不能单独使用该无参构造函数</span></span><br><span class="line"><span class="built_in">time_point</span>();</span><br><span class="line"><span class="comment">// 2. 构造一个对象，表示一个时间点，其中d的持续时间从epoch开始，需要和时钟类一起使用，不能单独使用该构造函数</span></span><br><span class="line"><span class="function"><span class="keyword">explicit</span> <span class="title">time_point</span><span class="params">( <span class="keyword">const</span> duration&amp; d )</span></span>;</span><br><span class="line"><span class="comment">// 3. 拷贝构造函数，构造与t相同时间点的对象，使用的时候需要指定模板参数</span></span><br><span class="line"><span class="function"><span class="keyword">template</span>&lt; class Duration2 &gt;</span></span><br><span class="line"><span class="function"><span class="title">time_point</span><span class="params">( <span class="keyword">const</span> time_point&lt;Clock,Duration2&gt;&amp; t )</span></span>;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>在这个类中除了构造函数还提供了另外一个 time_since_epoch() 函数，用来获得 1970 年 1 月 1 日到 time_point 对象中记录的时间经过的时间间隔（duration），函数原型如下：</p>
</blockquote>
<figure class="highlight cpp"><table><tr><td class="code"><pre><span class="line"><span class="function">duration <span class="title">time_since_epoch</span><span class="params">()</span> <span class="keyword">const</span></span>;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>除此之外，时间点 time_point 对象和时间段对象 duration 之间还支持直接进行算术运算（即加减运算），时间点对象之间可以进行逻辑运算，具体细节可以参考下面的表格：</p>
</blockquote>
<blockquote>
<p>其中 tp 和 tp2 是 time_point 类型的对象， dtn 是 duration 类型的对象。</p>
</blockquote>
<table>
<thead>
<tr>
<th align="left">描述</th>
<th align="center">操作</th>
<th align="center">返回值</th>
</tr>
</thead>
<tbody><tr>
<td align="left">复合赋值 (成员函数) operator+=</td>
<td align="center">tp += dtn</td>
<td align="center">*this</td>
</tr>
<tr>
<td align="left">复合赋值 (成员函数) operator-=</td>
<td align="center">tp -= dtn</td>
<td align="center">*this</td>
</tr>
<tr>
<td align="left">算术运算符 (非成员函数) operator+</td>
<td align="center">tp + dtn</td>
<td align="center">a time_point value</td>
</tr>
<tr>
<td align="left">算术运算符 (非成员函数) operator+</td>
<td align="center">dtn + tp</td>
<td align="center">a time_point value</td>
</tr>
<tr>
<td align="left">算术运算符 (非成员函数) operator-</td>
<td align="center">tp - dtn</td>
<td align="center">a time_point value</td>
</tr>
<tr>
<td align="left">算术运算符 (非成员函数) operator-</td>
<td align="center">ttp - tp2</td>
<td align="center">aduration value</td>
</tr>
<tr>
<td align="left">关系操作符 (非成员函数) operator==</td>
<td align="center">tp == tp2</td>
<td align="center">a bool value</td>
</tr>
<tr>
<td align="left">关系操作符 (非成员函数) operator!=</td>
<td align="center">tp != tp2</td>
<td align="center">a bool value</td>
</tr>
<tr>
<td align="left">关系操作符 (非成员函数) operator&lt;</td>
<td align="center">tp &lt; tp2</td>
<td align="center">a bool value</td>
</tr>
<tr>
<td align="left">关系操作符 (非成员函数) operator&gt;</td>
<td align="center">tp &gt; tp2</td>
<td align="center">a bool value</td>
</tr>
<tr>
<td align="left">关系操作符 (非成员函数) operator&gt;=</td>
<td align="center">tp &gt;= tp2</td>
<td align="center">a bool value</td>
</tr>
<tr>
<td align="left">关系操作符 (非成员函数) operator&lt;=</td>
<td align="center">tp &lt;= tp2</td>
<td align="center">a bool value</td>
</tr>
</tbody></table>
<p>由于该时间点类经常和下面要介绍的时钟类一起使用，所以在此先不举例，在时钟类的示例代码中会涉及到时间点类的使用，到此为止只需要搞明白时间点类的提供的这几个函数的作用就可以了。</p>
<h3 id="3-时钟-clocks"><a href="#3-时钟-clocks" class="headerlink" title="3. 时钟 clocks"></a>3. 时钟 clocks</h3><p>chrono 库中提供了获取当前的系统时间的时钟类，包含的时钟一共有三种：</p>
<ul>
<li>system_clock：系统的时钟，系统的时钟可以修改，甚至可以网络对时，因此使用系统时间计算时间差可能不准。</li>
<li>steady_clock：是固定的时钟，相当于秒表。开始计时后，时间只会增长并且不能修改，适合用于记录程序耗时</li>
<li>high_resolution_clock：和时钟类 steady_clock 是等价的（是它的别名）。</li>
</ul>
<p>在这些时钟类的内部有 time_point、duration、Rep、Period 等信息，基于这些信息来获取当前时间，以及实现 time_t 和 time_point 之间的相互转换。</p>
<table>
<thead>
<tr>
<th align="left">时钟类成员类型</th>
<th align="center">描述</th>
</tr>
</thead>
<tbody><tr>
<td align="left">rep</td>
<td align="center">表示时钟周期次数的有符号算术类型</td>
</tr>
<tr>
<td align="left">period</td>
<td align="center">表示时钟计次周期的 std::ratio 类型</td>
</tr>
<tr>
<td align="left">duration</td>
<td align="center">时间间隔，可以表示负时长</td>
</tr>
<tr>
<td align="left">time_point</td>
<td align="center">表示在当前时钟里边记录的时间点</td>
</tr>
</tbody></table>
<p>在使用chrono提供的时钟类的时候，不需要创建类对象，直接调用类的静态方法就可以得到想要的时间了。</p>
<h3 id="3-1-system-clock"><a href="#3-1-system-clock" class="headerlink" title="3.1 system_clock"></a>3.1 system_clock</h3><p>具体来说，时钟类 system_clock 是一个系统范围的实时时钟。system_clock 提供了对当前时间点 time_point 的访问，将得到时间点转换为 time_t 类型的时间对象，就可以基于这个时间对象获取到当前的时间信息了。</p>
<blockquote>
<p>system_clock 时钟类在底层源码中的定义如下：</p>
</blockquote>
<figure class="highlight cpp"><table><tr><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">system_clock</span> &#123;</span> <span class="comment">// wraps GetSystemTimePreciseAsFileTime/GetSystemTimeAsFileTime</span></span><br><span class="line">    <span class="keyword">using</span> rep                       = <span class="keyword">long</span> <span class="keyword">long</span>;</span><br><span class="line">    <span class="keyword">using</span> period                    = ratio&lt;<span class="number">1</span>, <span class="number">10&#x27;000&#x27;000</span>&gt;; <span class="comment">// 100 nanoseconds</span></span><br><span class="line">    <span class="keyword">using</span> duration                  = chrono::duration&lt;rep, period&gt;;</span><br><span class="line">    <span class="keyword">using</span> time_point                = chrono::time_point&lt;system_clock&gt;;</span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">constexpr</span> <span class="keyword">bool</span> is_steady = <span class="literal">false</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function">_NODISCARD <span class="keyword">static</span> time_point <span class="title">now</span><span class="params">()</span> <span class="keyword">noexcept</span> </span></span><br><span class="line"><span class="function">    </span>&#123; <span class="comment">// get current time</span></span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">time_point</span>(<span class="built_in">duration</span>(_Xtime_get_ticks()));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function">_NODISCARD <span class="keyword">static</span> <span class="keyword">__time64_t</span> <span class="title">to_time_t</span><span class="params">(<span class="keyword">const</span> time_point&amp; _Time)</span> <span class="keyword">noexcept</span> </span></span><br><span class="line"><span class="function">    </span>&#123; <span class="comment">// convert to __time64_t</span></span><br><span class="line">        <span class="keyword">return</span> duration_cast&lt;seconds&gt;(_Time.<span class="built_in">time_since_epoch</span>()).<span class="built_in">count</span>();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function">_NODISCARD <span class="keyword">static</span> time_point <span class="title">from_time_t</span><span class="params">(<span class="keyword">__time64_t</span> _Tm)</span> <span class="keyword">noexcept</span> </span></span><br><span class="line"><span class="function">    </span>&#123; <span class="comment">// convert from __time64_t</span></span><br><span class="line">        <span class="keyword">return</span> time_point&#123;seconds&#123;_Tm&#125;&#125;;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>通过以上源码可以了解到在 system_clock 类中的一些细节信息：</p>
</blockquote>
<ul>
<li>rep：时钟周期次数是通过整形来记录的 long long</li>
<li>period：一个时钟周期是 100 纳秒 ratio&lt;1, 10’000’000&gt;</li>
<li>duration：时间间隔为 rep*period 纳秒 chrono::duration&lt;rep, period&gt;</li>
<li>time_point：时间点通过系统时钟做了初始化 chrono::time_p- oint<system_clock>，里面记录了新纪元时间点</li>
</ul>
<blockquote>
<p>另外还可以看到 system_clock 类一共提供了三个静态成员函数：</p>
</blockquote>
<figure class="highlight cpp"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 返回表示当前时间的时间点。</span></span><br><span class="line"><span class="keyword">static</span> std::<span class="function">chrono::time_point&lt;std::chrono::system_clock&gt; <span class="title">now</span><span class="params">()</span> <span class="keyword">noexcept</span></span>;</span><br><span class="line"><span class="comment">// 将 time_point 时间点类型转换为 std::time_t 类型</span></span><br><span class="line"><span class="function"><span class="keyword">static</span> std::<span class="keyword">time_t</span> <span class="title">to_time_t</span><span class="params">( <span class="keyword">const</span> time_point&amp; t )</span> <span class="keyword">noexcept</span></span>;</span><br><span class="line"><span class="comment">// 将 std::time_t 类型转换为 time_point 时间点类型</span></span><br><span class="line"><span class="keyword">static</span> std::chrono::<span class="function">system_clock::time_point <span class="title">from_time_t</span><span class="params">( std::<span class="keyword">time_t</span> t )</span> <span class="keyword">noexcept</span></span>;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>比如，我们要获取当前的系统时间，并且需要将其以能够识别的方式打印出来，示例代码如下：</p>
</blockquote>
<figure class="highlight cpp"><table><tr><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;chrono&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> std;</span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> std::chrono;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="comment">// 新纪元1970.1.1时间</span></span><br><span class="line">    system_clock::time_point epoch;</span><br><span class="line"></span><br><span class="line">    duration&lt;<span class="keyword">int</span>, ratio&lt;<span class="number">60</span>*<span class="number">60</span>*<span class="number">24</span>&gt;&gt; <span class="built_in">day</span>(<span class="number">1</span>);</span><br><span class="line">    <span class="comment">// 新纪元1970.1.1时间 + 1天</span></span><br><span class="line">    <span class="function">system_clock::time_point <span class="title">ppt</span><span class="params">(day)</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">using</span> dday = duration&lt;<span class="keyword">int</span>, ratio&lt;<span class="number">60</span> * <span class="number">60</span> * <span class="number">24</span>&gt;&gt;;</span><br><span class="line">    <span class="comment">// 新纪元1970.1.1时间 + 10天</span></span><br><span class="line">    <span class="function">time_point&lt;system_clock, dday&gt; <span class="title">t</span><span class="params">(dday(<span class="number">10</span>))</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 系统当前时间</span></span><br><span class="line">    system_clock::time_point today = system_clock::<span class="built_in">now</span>();</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 转换为time_t时间类型</span></span><br><span class="line">    <span class="keyword">time_t</span> tm = system_clock::<span class="built_in">to_time_t</span>(today);</span><br><span class="line">    cout &lt;&lt; <span class="string">&quot;今天的日期是:    &quot;</span> &lt;&lt; <span class="built_in">ctime</span>(&amp;tm);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">time_t</span> tm1 = system_clock::<span class="built_in">to_time_t</span>(today+day);</span><br><span class="line">    cout &lt;&lt; <span class="string">&quot;明天的日期是:    &quot;</span> &lt;&lt; <span class="built_in">ctime</span>(&amp;tm1);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">time_t</span> tm2 = system_clock::<span class="built_in">to_time_t</span>(epoch);</span><br><span class="line">    cout &lt;&lt; <span class="string">&quot;新纪元时间:      &quot;</span> &lt;&lt; <span class="built_in">ctime</span>(&amp;tm2);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">time_t</span> tm3 = system_clock::<span class="built_in">to_time_t</span>(ppt);</span><br><span class="line">    cout &lt;&lt; <span class="string">&quot;新纪元时间+1天:  &quot;</span> &lt;&lt; <span class="built_in">ctime</span>(&amp;tm3);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">time_t</span> tm4 = system_clock::<span class="built_in">to_time_t</span>(t);</span><br><span class="line">    cout &lt;&lt; <span class="string">&quot;新纪元时间+10天: &quot;</span> &lt;&lt; <span class="built_in">ctime</span>(&amp;tm4);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>示例代码打印的结果为：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">今天的日期是:    Thu Apr  8 11:09:49 2021</span><br><span class="line">明天的日期是:    Fri Apr  9 11:09:49 2021</span><br><span class="line">新纪元时间:      Thu Jan  1 08:00:00 1970</span><br><span class="line">新纪元时间+1天:  Fri Jan  2 08:00:00 1970</span><br><span class="line">新纪元时间+10天: Sun Jan 11 08:00:00 1970</span><br></pre></td></tr></table></figure>

<h3 id="3-2-steady-clock"><a href="#3-2-steady-clock" class="headerlink" title="3.2 steady_clock"></a>3.2 steady_clock</h3><p>如果我们通过时钟不是为了获取当前的系统时间，而是进行程序耗时的时长，此时使用 syetem_clock 就不合适了，因为这个时间可以跟随系统的设置发生变化。在 C++11 中提供的时钟类 steady_clock 相当于秒表，只要启动就会进行时间的累加，并且不能被修改，非常适合于进行耗时的统计。</p>
<blockquote>
<p>steady_clock 时钟类在底层源码中的定义如下：</p>
</blockquote>
<figure class="highlight cpp"><table><tr><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">steady_clock</span> &#123;</span> <span class="comment">// wraps QueryPerformanceCounter</span></span><br><span class="line">    <span class="keyword">using</span> rep                       = <span class="keyword">long</span> <span class="keyword">long</span>;</span><br><span class="line">    <span class="keyword">using</span> period                    = nano;</span><br><span class="line">    <span class="keyword">using</span> duration                  = nanoseconds;</span><br><span class="line">    <span class="keyword">using</span> time_point                = chrono::time_point&lt;steady_clock&gt;;</span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">constexpr</span> <span class="keyword">bool</span> is_steady = <span class="literal">true</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// get current time</span></span><br><span class="line">    <span class="function">_NODISCARD <span class="keyword">static</span> time_point <span class="title">now</span><span class="params">()</span> <span class="keyword">noexcept</span> </span></span><br><span class="line"><span class="function">    </span>&#123; </span><br><span class="line">        <span class="comment">// doesn&#x27;t change after system boot</span></span><br><span class="line">        <span class="keyword">const</span> <span class="keyword">long</span> <span class="keyword">long</span> _Freq = _Query_perf_frequency(); </span><br><span class="line">        <span class="keyword">const</span> <span class="keyword">long</span> <span class="keyword">long</span> _Ctr  = _Query_perf_counter();</span><br><span class="line">        <span class="built_in"><span class="keyword">static_assert</span></span>(period::num == <span class="number">1</span>, <span class="string">&quot;This assumes period::num == 1.&quot;</span>);</span><br><span class="line">        <span class="keyword">const</span> <span class="keyword">long</span> <span class="keyword">long</span> _Whole = (_Ctr / _Freq) * period::den;</span><br><span class="line">        <span class="keyword">const</span> <span class="keyword">long</span> <span class="keyword">long</span> _Part  = (_Ctr % _Freq) * period::den / _Freq;</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">time_point</span>(<span class="built_in">duration</span>(_Whole + _Part));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>通过以上源码可以了解到在 steady_clock 类中的一些细节信息：</p>
</blockquote>
<ul>
<li>rep：时钟周期次数是通过整形来记录的 long long</li>
<li>period：一个时钟周期是 1 纳秒 nano</li>
<li>duration：时间间隔为 1 纳秒 nanoseconds</li>
<li>time_point：时间点通过系统时钟做了初始化 chrono::time_point<steady_clock></li>
</ul>
<blockquote>
<p>另外，在这个类中也提供了一个静态的 now () 方法，用于得到当前的时间点，函数原型如下：</p>
</blockquote>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">static std::chrono::time_point&lt;std::chrono::steady_clock&gt; now() noexcept;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>假设要测试某一段程序的执行效率，可以计算它执行期间消耗的总时长，示例代码如下：</p>
</blockquote>
<figure class="highlight cpp"><table><tr><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;chrono&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> std;</span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> std::chrono;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="comment">// 获取开始时间点</span></span><br><span class="line">    steady_clock::time_point start = steady_clock::<span class="built_in">now</span>();</span><br><span class="line">    <span class="comment">// 执行业务流程</span></span><br><span class="line">    cout &lt;&lt; <span class="string">&quot;print 1000 stars ....&quot;</span> &lt;&lt; endl;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">1000</span>; ++i)</span><br><span class="line">    &#123;</span><br><span class="line">        cout &lt;&lt; <span class="string">&quot;*&quot;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    cout &lt;&lt; endl;</span><br><span class="line">    <span class="comment">// 获取结束时间点</span></span><br><span class="line">    steady_clock::time_point last = steady_clock::<span class="built_in">now</span>();</span><br><span class="line">    <span class="comment">// 计算差值</span></span><br><span class="line">    <span class="keyword">auto</span> dt = last - start;</span><br><span class="line">    cout &lt;&lt; <span class="string">&quot;总共耗时: &quot;</span> &lt;&lt; dt.<span class="built_in">count</span>() &lt;&lt; <span class="string">&quot;纳秒&quot;</span> &lt;&lt; endl;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="3-3-high-resolution-clock"><a href="#3-3-high-resolution-clock" class="headerlink" title="3.3 high_resolution_clock"></a>3.3 high_resolution_clock</h3><p>high_resolution_clock 提供的时钟精度比 system_clock 要高，它也是不可以修改的。在底层源码中，这个类其实是 steady_clock 类的别名。</p>
<figure class="highlight cpp"><table><tr><td class="code"><pre><span class="line"><span class="keyword">using</span> high_resolution_clock = steady_clock;</span><br></pre></td></tr></table></figure>

<p>因此 high_resolution_clock 的使用方式和 steady_clock 是一样的，在此就不再过多进行赘述了。</p>
<h2 id="4-转换函数"><a href="#4-转换函数" class="headerlink" title="4. 转换函数"></a>4. 转换函数</h2><h3 id="4-1-duration-cast"><a href="#4-1-duration-cast" class="headerlink" title="4.1 duration_cast"></a>4.1 duration_cast</h3><p>duration_cast 是 chrono 库提供的一个模板函数，这个函数不属于 duration 类。通过这个函数可以对 duration 类对象内部的时钟周期 Period，和周期次数的类型 Rep 进行修改，该函数原型如下：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">template &lt;class ToDuration, class Rep, class Period&gt;</span><br><span class="line">  constexpr ToDuration duration_cast (const duration&lt;Rep,Period&gt;&amp; dtn);</span><br></pre></td></tr></table></figure>

<p>在源周期能准确地为目标周期所整除的场合（例如小时到分钟），浮点时长和整数时长间转型能隐式进行无需使用 duration_cast ，其他情况下都需要通过函数进行转换。</p>
<p>我们可以修改一下上面测试程序执行时间的代码，在代码中修改 duration 对象的属性：</p>
<figure class="highlight cpp"><table><tr><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;chrono&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> std;</span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> std::chrono;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">f</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    cout &lt;&lt; <span class="string">&quot;print 1000 stars ....&quot;</span> &lt;&lt; endl;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">1000</span>; ++i)</span><br><span class="line">    &#123;</span><br><span class="line">        cout &lt;&lt; <span class="string">&quot;*&quot;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    cout &lt;&lt; endl;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">auto</span> t1 = steady_clock::<span class="built_in">now</span>();</span><br><span class="line">    <span class="built_in">f</span>();</span><br><span class="line">    <span class="keyword">auto</span> t2 = steady_clock::<span class="built_in">now</span>();</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 整数时长：要求 duration_cast</span></span><br><span class="line">    <span class="keyword">auto</span> int_ms = duration_cast&lt;chrono::milliseconds&gt;(t2 - t1);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 小数时长：不要求 duration_cast</span></span><br><span class="line">    duration&lt;<span class="keyword">double</span>, ratio&lt;<span class="number">1</span>, <span class="number">1000</span>&gt;&gt; fp_ms = t2 - t1;</span><br><span class="line"></span><br><span class="line">    cout &lt;&lt; <span class="string">&quot;f() took &quot;</span> &lt;&lt; fp_ms.<span class="built_in">count</span>() &lt;&lt; <span class="string">&quot; ms, &quot;</span></span><br><span class="line">        &lt;&lt; <span class="string">&quot;or &quot;</span> &lt;&lt; int_ms.<span class="built_in">count</span>() &lt;&lt; <span class="string">&quot; whole milliseconds\n&quot;</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>示例代码输出的结果：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">print 1000 stars ....</span><br><span class="line">****************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************</span><br><span class="line">f() took 40.2547 ms, or 40 whole milliseconds</span><br></pre></td></tr></table></figure>

<h3 id="4-2-time-point-cast"><a href="#4-2-time-point-cast" class="headerlink" title="4.2 time_point_cast"></a>4.2 time_point_cast</h3><p>time_point_cast 也是 chrono 库提供的一个模板函数，这个函数不属于 time_point 类。函数的作用是对时间点进行转换，因为不同的时间点对象内部的时钟周期 Period，和周期次数的类型 Rep 可能也是不同的，一般情况下它们之间可以进行隐式类型转换，也可以通过该函数显示的进行转换，函数原型如下：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">template &lt;class ToDuration, class Clock, class Duration&gt;</span><br><span class="line">time_point&lt;Clock, ToDuration&gt; time_point_cast(const time_point&lt;Clock, Duration&gt; &amp;t);</span><br></pre></td></tr></table></figure>

<p>关于函数的使用，示例代码如下：</p>
<figure class="highlight cpp"><table><tr><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;chrono&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> std;</span><br><span class="line"></span><br><span class="line"><span class="keyword">using</span> Clock = chrono::high_resolution_clock;</span><br><span class="line"><span class="keyword">using</span> Ms = chrono::milliseconds;</span><br><span class="line"><span class="keyword">using</span> Sec = chrono::seconds;</span><br><span class="line"><span class="keyword">template</span>&lt;<span class="class"><span class="keyword">class</span> <span class="title">Duration</span>&gt;</span></span><br><span class="line"><span class="keyword">using</span> TimePoint = chrono::time_point&lt;Clock, Duration&gt;;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">print_ms</span><span class="params">(<span class="keyword">const</span> TimePoint&lt;Ms&gt;&amp; time_point)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    std::cout &lt;&lt; time_point.<span class="built_in">time_since_epoch</span>().<span class="built_in">count</span>() &lt;&lt; <span class="string">&quot; ms\n&quot;</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="function">TimePoint&lt;Sec&gt; <span class="title">time_point_sec</span><span class="params">(Sec(<span class="number">6</span>))</span></span>;</span><br><span class="line">    <span class="comment">// 无精度损失, 可以进行隐式类型转换</span></span><br><span class="line">    <span class="function">TimePoint&lt;Ms&gt; <span class="title">time_point_ms</span><span class="params">(time_point_sec)</span></span>;</span><br><span class="line">    <span class="built_in">print_ms</span>(time_point_ms);    <span class="comment">// 6000 ms</span></span><br><span class="line"></span><br><span class="line">    time_point_ms = TimePoint&lt;Ms&gt;(<span class="built_in">Ms</span>(<span class="number">6789</span>));</span><br><span class="line">    <span class="comment">// error，会损失精度，不允许进行隐式的类型转换</span></span><br><span class="line">    <span class="function">TimePoint&lt;Sec&gt; <span class="title">sec</span><span class="params">(time_point_ms)</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 显示类型转换,会损失精度。6789 truncated to 6000</span></span><br><span class="line">    time_point_sec = std::chrono::time_point_cast&lt;Sec&gt;(time_point_ms);</span><br><span class="line">    <span class="built_in">print_ms</span>(time_point_sec); <span class="comment">// 6000 ms</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>注意事项</strong>：关于时间点的转换如果没有没有精度的损失可以直接进行隐式类型转换，如果会损失精度只能通过显示类型转换，也就是调用 time_point_cast 函数来完成该操作。</p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">逝水无痕</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://hexo.zyjblogs.cn/posts/c++/library/date/1.html">https://hexo.zyjblogs.cn/posts/c++/library/date/1.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://hexo.zyjblogs.cn" target="_blank">逝水无痕の博客</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/c/">c++</a><a class="post-meta__tags" href="/tags/chrono/">chrono</a></div><div class="post_share"><div class="social-share" data-image="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/posts/c++/study/backend/1.html"><img class="prev-cover" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">C++后台</div></div></a></div><div class="next-post pull-right"><a href="/posts/c++/article/2022/02/07/1.html"><img class="next-cover" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">C++ 八股文（一）</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/posts/books/c/1.html" title="C++书单"><img class="cover" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-08-09</div><div class="title">C++书单</div></div></a></div><div><a href="/posts/c++/base/polymorphic/1.html" title="C++编译期多态与运行期多态"><img class="cover" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-02-07</div><div class="title">C++编译期多态与运行期多态</div></div></a></div><div><a href="/posts/c++/base/virtual/1.html" title="虚基类"><img class="cover" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-02-07</div><div class="title">虚基类</div></div></a></div><div><a href="/posts/c++/library/json/1.html" title="C/C++ 关于 cJson 库的使用"><img class="cover" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-02-07</div><div class="title">C/C++ 关于 cJson 库的使用</div></div></a></div><div><a href="/posts/c++/study/backend/1.html" title="C++后台"><img class="cover" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-02-07</div><div class="title">C++后台</div></div></a></div><div><a href="/posts/c++/article/2022/02/07/1.html" title="C++ 八股文（一）"><img class="cover" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-02-07</div><div class="title">C++ 八股文（一）</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="https://zyjblogs.cn/logo.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">逝水无痕</div><div class="author-info__description"></div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">11</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">标签</div><div class="length-num">8</div></a></div><div class="card-info-data-item is-center"><a href="/categories/"><div class="headline">分类</div><div class="length-num">5</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/zyjnicemoe"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/zyjnicemoe" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="mailto:1317453947@qq.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a><a class="social-icon" href="/atom.xml" target="_blank" title=""><i class="fas fa-rss"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content"><a target="_blank" rel="noopener" href="https://zyjblogs.cn">逝水无痕の博客https://zyjblogs.cn迁移到此</a></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#C-%E4%BD%BF%E7%94%A8-chrono-%E5%BA%93%E5%A4%84%E7%90%86%E6%97%A5%E6%9C%9F%E5%92%8C%E6%97%B6%E9%97%B4"><span class="toc-number">1.</span> <span class="toc-text">C++ 使用 chrono 库处理日期和时间</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1-%E6%97%B6%E9%97%B4%E9%97%B4%E9%9A%94-duration"><span class="toc-number">1.1.</span> <span class="toc-text">1. 时间间隔 duration</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-1-%E5%B8%B8%E7%94%A8%E7%B1%BB%E6%88%90%E5%91%98"><span class="toc-number">1.1.1.</span> <span class="toc-text">1.1 常用类成员</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-2-%E7%B1%BB%E7%9A%84%E4%BD%BF%E7%94%A8"><span class="toc-number">1.1.2.</span> <span class="toc-text">1.2 类的使用</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-%E6%97%B6%E9%97%B4%E7%82%B9-time-point"><span class="toc-number">1.1.3.</span> <span class="toc-text">2. 时间点 time point</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-%E6%97%B6%E9%92%9F-clocks"><span class="toc-number">1.1.4.</span> <span class="toc-text">3. 时钟 clocks</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-1-system-clock"><span class="toc-number">1.1.5.</span> <span class="toc-text">3.1 system_clock</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-2-steady-clock"><span class="toc-number">1.1.6.</span> <span class="toc-text">3.2 steady_clock</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-3-high-resolution-clock"><span class="toc-number">1.1.7.</span> <span class="toc-text">3.3 high_resolution_clock</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4-%E8%BD%AC%E6%8D%A2%E5%87%BD%E6%95%B0"><span class="toc-number">1.2.</span> <span class="toc-text">4. 转换函数</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#4-1-duration-cast"><span class="toc-number">1.2.1.</span> <span class="toc-text">4.1 duration_cast</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-2-time-point-cast"><span class="toc-number">1.2.2.</span> <span class="toc-text">4.2 time_point_cast</span></a></li></ol></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/posts/c++/base/polymorphic/1.html" title="C++编译期多态与运行期多态"><img src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="C++编译期多态与运行期多态"/></a><div class="content"><a class="title" href="/posts/c++/base/polymorphic/1.html" title="C++编译期多态与运行期多态">C++编译期多态与运行期多态</a><time datetime="2022-02-06T16:00:00.000Z" title="发表于 2022-02-07 00:00:00">2022-02-07</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/posts/c++/base/virtual/1.html" title="虚基类"><img src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="虚基类"/></a><div class="content"><a class="title" href="/posts/c++/base/virtual/1.html" title="虚基类">虚基类</a><time datetime="2022-02-06T16:00:00.000Z" title="发表于 2022-02-07 00:00:00">2022-02-07</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/posts/c++/library/json/1.html" title="C/C++ 关于 cJson 库的使用"><img src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="C/C++ 关于 cJson 库的使用"/></a><div class="content"><a class="title" href="/posts/c++/library/json/1.html" title="C/C++ 关于 cJson 库的使用">C/C++ 关于 cJson 库的使用</a><time datetime="2022-02-06T16:00:00.000Z" title="发表于 2022-02-07 00:00:00">2022-02-07</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/posts/c++/study/backend/1.html" title="C++后台"><img src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="C++后台"/></a><div class="content"><a class="title" href="/posts/c++/study/backend/1.html" title="C++后台">C++后台</a><time datetime="2022-02-06T16:00:00.000Z" title="发表于 2022-02-07 00:00:00">2022-02-07</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/posts/c++/library/date/1.html" title="C++ 使用 chrono 库处理日期和时间"><img src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="C++ 使用 chrono 库处理日期和时间"/></a><div class="content"><a class="title" href="/posts/c++/library/date/1.html" title="C++ 使用 chrono 库处理日期和时间">C++ 使用 chrono 库处理日期和时间</a><time datetime="2022-02-06T16:00:00.000Z" title="发表于 2022-02-07 00:00:00">2022-02-07</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2019 - 2022 By 逝水无痕</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text"><div><img style="padding-top:2px" src="https://sp-ao.shortpixel.ai/client/q_glossy,ret_img/https://zyjblogs.cn/img/icp.png"><a class="banquan" style="color:#000" href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=鄂ICP备19023232号" target="_blank" data-pjax-state="">鄂ICP备19023232号</a></div></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script src="/js/search/local-search.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"></div><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = true;
POWERMODE.mobile = false;
document.body.addEventListener('input', POWERMODE);
</script><script src="https://cdn.jsdelivr.net/npm/pjax/pjax.min.js"></script><script>let pjaxSelectors = [
  'title',
  '#config-diff',
  '#body-wrap',
  '#rightside-config-hide',
  '#rightside-config-show',
  '.js-pjax'
]

if (false) {
  pjaxSelectors.unshift('meta[property="og:image"]', 'meta[property="og:title"]', 'meta[property="og:url"]')
}

var pjax = new Pjax({
  elements: 'a:not([target="_blank"]):not([href="/music/"]):not([href="/no-pjax/"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:send', function () {

  // removeEventListener scroll 
  window.removeEventListener('scroll', window.tocScrollFn)
  window.removeEventListener('scroll', scrollCollect)

  typeof preloader === 'object' && preloader.initLoading()
  
  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  document.querySelectorAll('script[data-pjax]').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof chatBtnFn === 'function' && chatBtnFn()
  typeof panguInit === 'function' && panguInit()

  // google analytics
  typeof gtag === 'function' && gtag('config', '', {'page_path': window.location.pathname});

  // baidu analytics
  typeof _hmt === 'object' && _hmt.push(['_trackPageview',window.location.pathname]);

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // Analytics
  if (false) {
    MtaH5.pgv()
  }

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()

  typeof preloader === 'object' && preloader.endLoading()
})

document.addEventListener('pjax:error', (e) => {
  if (e.request.status === 404) {
    pjax.loadUrl('/404.html')
  }
})</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>